package com.wx.plugin.mvc;

import com.wx.plugin.constant.CharConstant;
import com.wx.plugin.util.HTTPUtil;
import com.wx.plugin.util.JvmUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("url", req.getRequestURL() + "  " + req.getMethod());
        mav.addObject("headers", HTTPUtil.showHeaderString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("cookies", HTTPUtil.showCookieString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("params", HTTPUtil.showParamsString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("message", e.getMessage());
        mav.addObject("exception", JvmUtil.printHTMLStackTrace(e, CharConstant.HTML_NEW_LINE_CHAR));
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

}
